package Game;

import java.util.Scanner;

import Player.HumanPlayer;
import Player.Player;
import Player.SimplePlayer;

/**
 * controls game flow
 * @author Jose
 *
 */
public class Dealer 
{	
	private Deck deck;
	private Stack stack;
	private Bufu rules;
	private HumanPlayer p1,p2;
	private boolean gameInProgress;
	private int currPlayer;
	private HumanPlayer[] players = new HumanPlayer[2];
	
	
	public Dealer()
	{
		deck = new Deck();
		deck.shuffle();
		stack = new Stack();
		p1 = new HumanPlayer();
		p1.setPlayerID(1);
		players[0] = p1;
		p2 = new HumanPlayer();
		p2.setPlayerID(2);	
		players[1] = p2;		
	}
	
	/**
	 * deal cards to players at the start of a game
	 */
	public void deal()
	{
		for(int i = 0; i<6;i++)
		{
			p1.addCardB(deck.dealCard());
			p2.addCardB(deck.dealCard());
						
		}
		for(int j =0; j<3; j++)
		{
			p1.addCardH(deck.dealCard());
			p2.addCardH(deck.dealCard());
		}
		p1.sortCards();
		p2.sortCards();		
	}
	
	/**
	 * starts a game. a random player starts
	 */
	public void doNewGame()
	{
		gameInProgress = true;
		deal();
		start();					
	}
	
	public int getCurrPlayer()
	{
		return currPlayer;
	}
	
	public void screen()
	{
		int player = currPlayer+1;
		System.out.println("Its player's " + player +" turn");
		System.out.println("player's hand: " + players[currPlayer].getHand().toString());
		System.out.println("player's board: " + players[currPlayer].getBoard().toString());
		System.out.println("Top stack card: " + stack.toString());
		System.out.println("select card to play");
	}
	
	/**
	 * randomly selects a player to start.
	 * still to implement
	 */
	public int start()
	{
		currPlayer = 0;
		return currPlayer;
	}
	
	/**
	 * determines the end of a game when a player
	 * runs out of cards.
	 * still to implement
	 */
	public boolean end()
	{
		return false;
	}
	
	public boolean check(int m)
	{		
		return rules.canPlay(stack.getTopCard(), players[getCurrPlayer()].getHand().getCard(m));
	}
	
	/**
	 * makes a player move
	 */
	public Card play(int p, int m)
	{
		Card move = null;
		int a = m - 1;
		move = players[p].getNextMove(a);		
		stack.addCard(move);
		players[p].addCardH(deck.dealCard());
		players[p].sortCards();
		if(currPlayer == 0)
		{
			currPlayer = 1;
		}
		else
		{
			currPlayer = 0;
		}
		
		/*else
		{
			move = players[p].getNextMove(stack.getTopCard());
		}*/
		return move;

	}
	
	public void game()
	{
		Scanner in = new Scanner(System.in);
		while(!end())
		{			
			screen();
			int move = in.nextInt();
			if(stack.getSize() > 0)
			{				
				if(check(move))
				{					
					play(getCurrPlayer(),move);
				}
				else
				{
					System.out.println("move is not valid, try another");
					game();
				}
			}
			else
			{
				play(getCurrPlayer(),move);
			}
		}
	}
	
	
	
}
